/*
 *    MiscUtils.java
 *    Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
 *    @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package moa.core;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Random;

import weka.core.Utils;

public class MiscUtils {

	public static int chooseRandomIndexBasedOnWeights(double[] weights,
			Random random) {
		double probSum = Utils.sum(weights);
		double val = random.nextDouble() * probSum;
		int index = 0;
		double sum = 0.0;
		while ((sum <= val) && (index < weights.length)) {
			sum += weights[index++];
		}
		return index - 1;
	}

	public static int poisson(double c, Random random) {
		int x = 0;
		double t = 0.0;
		while (true) {
			t -= Math.log(random.nextDouble()) / c;
			if (t > 1.0) {
				return x;
			}
			x++;
		}
	}

	public static String getStackTraceString(Exception ex) {
		StringWriter stackTraceWriter = new StringWriter();
		ex.printStackTrace(new PrintWriter(stackTraceWriter));
		return "*** STACK TRACE ***\n" + stackTraceWriter.toString();
	}
	
	public static double exponentialDistribution(double lambda, Random random){
			// Returns an exponentially distributed, positive, random deviate of lambda mean.
			return -Math.log(random.nextDouble())/lambda;
	}
		
	public static double normalDistribution(double mean, double variance, Random random){
			// Returns a normal distributed, positive, random deviate of mean "mean" and variance "variance".
			return random.nextGaussian()* Math.sqrt(variance) + mean;
	}
		
	public static double uniformDistribution(Random random){
			// Returns an uniform distributed, positive, random deviate from 0 to 1
			return random.nextDouble();
	}

}
